package me.flyray.bsin.context;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import me.flyray.bsin.utils.ValidatorUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Log4j2
public class BsinServiceContext {
  public static <T> T getReqBodyDto(
      Class<T> dtoClassType, Map<String, Object> map, Class<?>... groups) {
    T obj = BeanUtil.copyProperties(map, dtoClassType);
    ValidatorUtils.validate(obj, groups);
    return obj;
  }

  private static <T> List<T> getReqBodyDtoList(
      String fieldName,
      Class<T> dtoClassType,
      Map<String, Object> map,
      Boolean withLoginInfo,
      Class<?>... groups) {
    if (!map.containsKey(fieldName)) {
      return Collections.emptyList();
    }
    List<T> collection = JSON.parseArray(JSON.toJSONString(map.get(fieldName)), dtoClassType);
    collection.forEach(
        item -> {
          if (withLoginInfo) {
            BeanUtil.copyProperties(
                LoginInfoContextHelper.getLoginUser(),
                item,
                CopyOptions.create().ignoreNullValue());
          }
          ValidatorUtils.validate(item, groups);
        });
    return collection;
  }

  public static <T> List<T> getReqBodyDtoList(
      String fieldName, Class<T> dtoClassType, Map<String, Object> map, Class<?>... groups) {
    return getReqBodyDtoList(fieldName, dtoClassType, map, Boolean.FALSE, groups);
  }

  public static <T> List<T> getReqBodyDtoListWithLoginInfo(
      String fieldName, Class<T> dtoClassType, Map<String, Object> map, Class<?>... groups) {
    return getReqBodyDtoList(fieldName, dtoClassType, map, Boolean.TRUE, groups);
  }

  public static <T> T bisId(Class<T> dtoClassType, Map<String, Object> map) {
    BaseService.bsinId(dtoClassType, map);
    String jsonStr = JSON.toJSONString(map);
    T obj = JSON.parseObject(jsonStr, dtoClassType);
    return obj;
  }
}
